# coding=UTF-8

'''
持久层
    -数据准备
    -把用例从工作簿中提取出来
'''

import xlrd
from my_test.tools.tools import *


class Deal_data:

    @print_exception
    def get_case(self, xls):
        '''
        收集测试用例，数据转换为可用
        :param xls:
        :return:
        '''
        my_cases = []
        datas = xlrd.open_workbook(xls).sheet_by_index(0)
        for i in range(1, datas.nrows):
            item = datas.row_values(i)
            case = Case(id=item[0], moudle=item[1], disc=item[2], method=item[3], url=item[4],
                        headers=self.__dael_headers(item[5]), body=self.__deal_body(item[6]), exp=item[7], flag=item[8],
                        prepose=item[9])
            my_cases.append(case)
        return my_cases

    @print_exception
    def __dael_headers(self, headers: str):
        '''
        处理 headers 为 dict
        :param headers:
        :return:
        '''
        head = {}
        if headers != '':
            str = headers.splitlines()
            for item in str:
                key, values = item.split(':', 1)
                head[key.strip()] = values.strip()
            return head
        else:
            return None

    @print_exception
    def __deal_body(self, body: str):
        '''
        处理 body 为 dict
        :param body:
        :return:
        '''
        data = {}
        if body == '':
            return None
        else:
            if '||' in body:
                item = body.split('\n')
            else:
                str = body.split('&')
                for item in str:
                    key, values = item.split('=', 1)
                    data[key] = values
                return data


class Case:
    '''
    用来储存用例，每个实例化对象就是一条用例
    '''

    def __init__(self, id, moudle, disc, method, url, headers, body, exp, flag, prepose):
        self.id = id
        self.moudle = moudle
        self.disc = disc
        self.method = method
        self.url = url
        self.headers = headers
        self.body = body
        self.exp = exp
        self.flag = flag
        self.prepose = prepose
